package com.dongdongshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.data.Result;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

@Controller
@RequestMapping("client")
public class ClientController {

    @RequestMapping("getTianQi")
    @ResponseBody
    public Result getTianQi(){
        CloseableHttpClient client = null;
        try {
            String address = getAddress();
            client = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet("http://autodev.openspeech.cn/csp/api/v2.1/weather?openId=aiuicus&clientType=android&sign=android&city=" + address + "&latitude=39.902895&longitude=116.427915&needMoreData=true&pageNo=1&pageSize=7");
            CloseableHttpResponse respones = client.execute(httpGet);
            //获取响应实体
            HttpEntity entity = respones.getEntity();
            String s = EntityUtils.toString(entity, "utf-8");
            JSONObject o = JSONObject.parseObject(s);
            Object data = o.get("data");
            String s1 = JSONObject.toJSONString(data);
            JSONObject jsonObject = JSONObject.parseObject(s1);
            return Result.OK().setData(jsonObject);
        }catch (Exception e){
            return Result.ERROR();
        }finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String getAddress(){
        String s = "";
        try {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet("https://www.mxnzp.com/api/ip/self?app_id=qhtllynonlrhrtqd&app_secret=cFptdDFQS1kwcUNWaE80cDVoQ0FQZz09");
            CloseableHttpResponse respones = client.execute(httpGet);
            //获取响应实体
            HttpEntity entity = respones.getEntity();
            s = EntityUtils.toString(entity, "utf-8");
            JSONObject jsonObject = JSONObject.parseObject(s);
            Object data = jsonObject.get("data");
            String s1 = JSONObject.toJSONString(data);
            JSONObject jsonObject1 = JSONObject.parseObject(s1);
            Object province = jsonObject1.get("province");
            s = province.toString();
        }catch (Exception e){

        }
        return s;
    }
}
